﻿using AutoMapper;
using FarmSmartSleep.Common.Domain.RBACFile;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;

namespace R.FarmSmartSleep.RBAC.API.Apliction.Command
{
    /// <summary>
    /// 添加手机验证码
    /// </summary>
    public class PhoneCaptchaCreateHandler:IRequestHandler<PhoneCaptchaCreateCommon, Result>
    {
        private readonly IBaseRepository<PhoneCaptcha> phoneCaptchaRep;
        private readonly IMapper mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        public PhoneCaptchaCreateHandler(IBaseRepository<PhoneCaptcha> phoneCaptchaRep, IMapper mapper)
        {
            this.phoneCaptchaRep = phoneCaptchaRep;
            this.mapper = mapper;
        }

        public async Task<Result> Handle(PhoneCaptchaCreateCommon request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CodeEnum.add };
            try
            {
                var phonecaptcha = mapper.Map<PhoneCaptcha>(request);
                var n = new Random();

                phonecaptcha.Captcha = n.Next(1000, 999999).ToString();

                var list = await phoneCaptchaRep.AddAsync(phonecaptcha);
                if(list>0)
                {
                    result.Messege = "添加成功";
                    result.Code = (int)CodeEnum.success;
                }
                else
                {
                    result.Messege = "添加失败";
                } 
            }
            catch (Exception)
            {
                result.Messege = "添加失败";
                throw;
            }
            return result;
        }
    }
}
